laravel 8 captcha

Addcaptcha

Sure! Below is an example of how to implement a simple CAPTCHA in Laravel 8. We'll use the popular Google reCAPTCHA service to add CAPTCHA functionality to a form in a Laravel application.


Step 1: Set Up Google reCAPTCHA
Visit the Google reCAPTCHA website (https://www.google.com/recaptcha) and sign up for an API key. You'll receive a Site Key and a Secret Key.


Step 2: Create a New Laravel Project (if you haven't already)
Open your terminal or command prompt, navigate to your development directory, and create a new Laravel project using Composer:


```bash

composer create-project laravel/laravel laravel-captcha-demo

cd laravel-captcha-demo

```


Step 3: Install and Configure Laravel reCAPTCHA Package
Laravel has various packages that simplify the integration of reCAPTCHA. For this example, we'll use the "anhskohbo/no-captcha" package, which can be installed via Composer:


```bash

composer require anhskohbo/no-captcha

```


After the package is installed, open the `config/app.php` file and add the following line to the `providers` array:


```php

Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

```


Next, add the following line to the `aliases` array:


```php

'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,

```


Step 4: Add Google reCAPTCHA Keys to .env
Open the `.env` file and add your Google reCAPTCHA keys:


```dotenv

NOCAPTCHA_SECRET=your-secret-key

NOCAPTCHA_SITEKEY=your-site-key

```


Step 5: Create a CAPTCHA-enabled Form

Create a new form that includes the reCAPTCHA widget. For this example, let's create a contact form.


First, create a route to handle the contact form:


```php

// routes/web.php

use Illuminate\Support\Facades\Route;


Route::get('/contact', function () {

return view('contact');

});


Route::post('/contact', function (Illuminate\Http\Request $request) {

$request->validate([

'name' => 'required|string',

'email' => 'required|email',

'message' => 'required|string',

'g-recaptcha-response' => 'required|captcha',

]);


// Process the contact form data and send an email, etc.


return redirect('/contact')->with('success', 'Message sent successfully!');

});

```


Next, create the `contact.blade.php` file in the `resources/views` directory:


```html





Contact Form with CAPTCHA

{!! NoCaptcha::renderJs() !!}



Contact Us


@if (session('success'))

{{ session('success') }}

@endif



@csrf







{!! NoCaptcha::display() !!}






```


Step 6: Test the CAPTCHA-enabled Form
Start your local development server:


```bash

php artisan serve

```


Visit `http://localhost:8000/contact` in your web browser, and you should see the contact form with the reCAPTCHA widget. When the form is submitted, it will validate the CAPTCHA response along with the other form fields.


That's it! You now have a CAPTCHA-enabled form in your Laravel 8 application, protecting it from automated bots and spam submissions.